package com.beidouin.sensortest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.HardWare.PCF8591;
import com.friendlyarm.AndroidSDK.FileCtlEnum;
import com.friendlyarm.AndroidSDK.GPIOEnum;
import com.friendlyarm.AndroidSDK.HardwareControler;

import static com.HardWare.PCF8591.ADC_Init;

public class JoystickActivity extends AppCompatActivity implements Runnable{

    TextView adValue_y,adValue_x,buttonSta;//aa11,aa22;
    int devFD=-1;
    Handler handler;
    int channel;
    Thread t = new Thread(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_joystick);
        adValue_y= (TextView) findViewById(R.id.adval_y);
        adValue_x= (TextView) findViewById(R.id.adval_x);

        buttonSta= (TextView) findViewById(R.id.button_txv);
        devFD = HardwareControler.open("/dev/i2c-0", FileCtlEnum.O_RDWR);
        ADC_Init(devFD);
        channel=0;
        HardwareControler.exportGPIOPin(73);//使能端口
        HardwareControler.setGPIODirection(73, GPIOEnum.IN);//设置GPIO为输入模式

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 0x101) {
                    adValue_y.setText(" "+msg.getData().getInt("adc0"));
                    adValue_x.setText(" "+msg.getData().getInt("adc1"));
                    buttonSta.setText(msg.getData().getBoolean("button")?"已按下":"未按下");
                }
                super.handleMessage(msg);
            }
        };
        t.start();
    }


    @Override
    protected void onDestroy() {
        HardwareControler.close(devFD);
        //将线程销毁掉
        t.interrupt();
        super.onDestroy();
    }

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted())
        {
            Message m=handler.obtainMessage();
            boolean keydown;
            if (HardwareControler.getGPIOValue(73) == GPIOEnum.LOW) {
                keydown=true;
            } else {
                keydown=false;
            }
            Bundle bundle =new Bundle();
            m.what=0x101;
            int adc0,adc1;
            int[] adc=new int[4];
            PCF8591.set_ADC_Channel(devFD,0);
            adc0=PCF8591.readADC_bychannel(devFD);
            PCF8591.set_ADC_Channel(devFD,1);
            adc1=PCF8591.readADC_bychannel(devFD);
            bundle.putBoolean("button", keydown);
            bundle.putInt("adc0", adc0);
            bundle.putInt("adc1", adc1);
            m.setData(bundle);
            handler.sendMessage(m);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}